home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / linux.68k / docs / dd-dri~1.z / dd-dri~1
Encoding:
Text File  |  1993-04-12  |  32.6 KB  |  948 lines

  1. ************************************************************
  2. *                                                          *
  3. *    Guide To Linux Driver Writing -- Character Devices    *
  4. *                                                          *
  5. *                            or,                           *
  6. *                                                          *
  7. *         The Wacky World of Driver Development (I)        *
  8. *                                                          *
  9. *                 Last Revision: Apr 11, 1993              *
  10. *                                                          *
  11. ************************************************************
  12.  
  13. This document (C) 1993 Robert Baruch.  This document may be freely 
  14. copied as long as the entire title, copyright, this notice, and all of
  15. the introduction are included along with it.  Suggestions, criticisms,
  16. and comments to baruch@nynexst.com.  This document, nor the work
  17. performed by Robert Baruch using Linux, nor the results of said work
  18. are connected in any way to any of the Nynex companies.  Information
  19. may settle during transportation.  This product should not be used
  20. in conjunction with a dietary regime except under supervision by your
  21. doctor.
  22.  
  23. Right, now that that's over with, let's get into the fun stuff!
  24.  
  25. ========================
  26.      Introduction
  27. ========================
  28.  
  29. There is a companion guide to this Guide, the Linux Character Device
  30. Tutorial.  This tutorial contains working examples of driver code.  It
  31. introduces the reader gently into each aspect of character device driver
  32. writing through experiments which are carried out by the programmer.
  33.  
  34. This Guide should serve as a reference to both beginning and advanced
  35. driver writers.
  36.  
  37. -=-=-=-=-=-=-
  38.  
  39. Some words of thanks:
  40.  
  41. Many thanks to:
  42.  
  43.  Donald J. Becker (becker@metropolis.super.org)
  44.  Don Holzworth (donh@gcx1.ssd.csd.harris.com)
  45.  Michael Johnson (johnsonm@stolaf.edu)
  46.  Karl Heinz Kremer (khk@raster.kodak.com)
  47.  All the driver writers!
  48.  
  49. ...and of course, Linus "Linux" Torvalds and all the guys who helped
  50.  develop Linux into a BLOODY KICKIN' O/S!
  51.  
  52. -=-=-=-=-=-=-
  53.  
  54. ...and now a word of warning:
  55.  
  56. Messing about with drivers is messing with the kernel.  Drivers are run
  57. at the kernel level, and as such are not subject to scheduling.  Further,
  58. drivers have access to various kernel structures.  Before you actually
  59. write a driver, be *damned* sure of what you are doing, lest you end
  60. up having to re-format your harddrive and re-install Linux!
  61.  
  62. The information in this Guide is as up-to-date as I could make it.  It also
  63. has no stamp of approval whatsoever by any of the designers of the kernel.
  64. I am not responsible for damage caused to anything as a result of using this
  65. Guide.
  66.  
  67. ========================
  68.   End of Introduction
  69. ========================
  70.  
  71. Kernal-callable functions:
  72. --------------------------
  73.  
  74. Note:  There is no close for a character device.  There is only release.
  75. See the file data structure below to find out how to determine the number
  76. of processes which have the device open.
  77.  
  78. -=-=-=-=-=-=-=-
  79.  
  80. init : Initializes the driver on bootup.
  81.  
  82.   unsigned long driver_init(unsigned long kmem_start, unsigned long kmem_end)
  83.  
  84. Arguments: kmem_start -- the start of kernel memory
  85.            kmem_end   -- the end of kernel memory
  86.  
  87. Returns: The new start of kernel memory.  This will be different from the
  88.   kmem_start argument if you want to allocate memory for the driver.
  89.  
  90. The arguments you use depends on what you want to do.  Remember that since
  91. you are going to add your init function to kernel/chr_dev/mem.c, you can
  92. make your call anything you like, but you have access to the kernel memory
  93. start and end.
  94.  
  95. Generally, the init function initializes the driver and hardware, and
  96. displays some message telling of the availability of the driver and
  97. hardware.  In addition, the register_chrdev function is usually called here.
  98.  
  99.  
  100. **************
  101. open : Open a device
  102.  
  103.   static int driver_open(struct inode * inode, struct file * file)
  104.  
  105. Arguments: inode    -- pointer to the inode structure for this device
  106.            file     -- pointer to the file structure for this device
  107.  
  108. Returns: 0 on success,
  109.          -errno on error.
  110.  
  111. This function is called whenever a process performs open (or fopen) on
  112. the device special file.  If there is no open function for the driver,
  113. nothing spectacular happens.  As long as the /dev file exists, the
  114. open will succeed.
  115.  
  116.  
  117. **************
  118. read : Read from a device
  119.  
  120.   static int driver_read(struct inode * inode, struct file * file, 
  121.                          char * buffer, int count)
  122.  
  123. Arguments: inode    -- pointer to the inode structure for this device
  124.            file     -- pointer to the file structure for this device
  125.            buffer   -- pointer to the buffer in user space to read into
  126.            count    -- the number of bytes to read
  127.  
  128. Returns: -errno on error
  129.          >=0 : the number of bytes actually read
  130.  
  131. If there is no read function for the driver, read calls will return EINVAL.
  132.  
  133.  
  134. **************
  135. write : Write to a device
  136.  
  137.   static int driver_write(struct inode * inode, struct file * file, 
  138.                           char * buffer, int count)
  139.  
  140. Arguments: inode    -- pointer to the inode structure for this device
  141.            file     -- pointer to the file structure for this device
  142.            buffer   -- pointer to the buffer in user space to write from
  143.            count    -- the number of bytes to write
  144.  
  145. Returns: -errno on error
  146.          >=0 : the number of bytes actually written
  147.  
  148. If there is no write function for the driver, write calls will return
  149. EINVAL.
  150.  
  151.  
  152. **************
  153. lseek : Change the position offset of the device
  154.  
  155.   static int driver_lseek(struct inode * inode, struct file * file,
  156.                           off_t offset, int origin)
  157.  
  158. Arguments: inode    -- pointer to the inode structure for this device
  159.            file     -- pointer to the file structure for this device
  160.            offset   -- offset from origin to move to (bytes)
  161.            origin   -- origin to move from :
  162.                        0 = from origin 0 (beginning)
  163.                        1 = from current position
  164.                        2 = from end
  165.  
  166. Returns: -errno on error
  167.          >=0 : the position after the move
  168.  
  169. See Also: Data Structure 'file'
  170.  
  171. If there is no lseek function for the driver, the kernel will take the default
  172. seek action, which is to alter the file->f_pos element.  For origins of 2,
  173. the default action results in -EINVAL if file->f_inode is NULL, or it
  174. sets file->f_pos to file->f_inode->i_size + offset otherwise.
  175.  
  176.  
  177. **************
  178. ioctl : Various device-dependent services
  179.  
  180.   static int driver_ioctl(struct inode *inode, struct file *file,
  181.                           unsigned int cmd, unsigned long arg)
  182.  
  183. Arguments: inode    -- pointer to the inode structure for this device
  184.            file     -- pointer to the file structure for this device
  185.            cmd      -- the user-defined command to perform
  186.            arg      -- the user-defined argument.  You may use this
  187.                        as a pointer to user space, since sizeof(long)==
  188.                        sizeof(void *).
  189.  
  190. Returns: -errno on error
  191.          >=0 : whatever you like! (user-defined)
  192.  
  193. For cmd, FIOCLEX, FIONCLEX, FIONBIO, and FIOASYNC are already defined.
  194. See the file linux/fs/ioctl.c, sys_ioctl to find out what they do.
  195. If there is no ioctl call for the driver, and the ioctl command performed
  196. is not one of the four types listed here, ioctl will return -EINVAL.
  197.  
  198.  
  199. **************
  200. select : Performs the select call on the device:
  201.  
  202.   static int driver_select(struct inode *inode, struct file *file, 
  203.                            int sel_type, select_table * wait)
  204.  
  205. Arguments: inode    -- pointer to the inode structure for this device
  206.            file     -- pointer to the file structure for this device
  207.            sel_type -- the select type to perform :
  208.                         SEL_IN (read)
  209.                         SEL_OUT (write)
  210.                         SEL_EX (exception)
  211.            wait     -- see the section "Some Notes" for select.
  212.  
  213. Returns: 0 if the device is not ready to perform the sel_type operation
  214.          !=0 if it is.
  215.  
  216. See the "Some Notes" section 'way below on information on how to use
  217. the select call in drivers.  If there is no select call for the driver,
  218. select will act as if the driver is ready for the operation.
  219.  
  220.  
  221. **************
  222. release : Release device (no process holds it open)
  223.  
  224.   static void driver_release(struct inode * inode, struct file * file)
  225.  
  226. Arguments: inode    -- pointer to the inode structure for this device
  227.            file     -- pointer to the file structure for this device
  228.  
  229. The release call is activated only when the process closes the device as
  230. many times as it has opened it.  That is, if the process has opened the
  231. device five times, then only when close is called for the fifth time
  232. will release be called (that is, provided there were no more calls to open!).  
  233. If there is no release call for the driver, nothing spectacular happens.
  234.  
  235.  
  236. **************
  237. readdir : Get the next directory entry
  238.  
  239.   static int driver_readdir(struct inode *inode, struct file *file, 
  240.                             struct dirent *dirent, int count)
  241.  
  242. Arguments: inode    -- pointer to the inode structure for this device
  243.            file     -- pointer to the file structure for this device
  244.            dirent   -- pointer to a dirent ("directory entry") structure
  245.            count    -- number of entries to read (currently always 1)
  246.  
  247. Returns: 0 on success
  248.          -errno on failure.
  249.  
  250. If there is no readdir function for the driver, readdir will return 
  251. -ENOTDIR.  This is really for file systems, but you can probably use
  252. it for whatever you like in a non-fs device, as long as you return
  253. a dirent structure.
  254.  
  255. See Also: dirent (data structure)
  256.  
  257.  
  258. **************
  259. mmap : Forget this.  According to the source (src/linux/mm/mmap.c),
  260.        for character devices only /dev/[k]mem may be mapped.
  261.        Besides, I'm not too clear on what it will do.
  262.  
  263.  
  264. ----------------------------------------------------------------------
  265.  
  266. Data structures:
  267. ----------------
  268.  
  269. dirent : Information about files in a directory.
  270.  
  271. #include <linux/dirent.h>
  272.  
  273. struct dirent {
  274.         long            d_ino;                /* Inode of file */
  275.         off_t           d_off;
  276.         unsigned short  d_reclen;
  277.         char            d_name[NAME_MAX+1];   /* Name of file */
  278. };
  279.  
  280.  
  281. **************
  282. file : Information about open files
  283.  
  284. According to the Hacker's Guide to Linux, this structure is mainly used
  285. for writing filesystems, not drivers.  However, there is no reason it
  286. cannot be used by drivers.
  287.  
  288. #include <linux/fs.h>
  289.  
  290. struct file {
  291.         mode_t f_mode;
  292.         dev_t f_rdev;                   /* needed for /dev/tty */
  293.         off_t f_pos;                    /* Curr. posn in file */
  294.         unsigned short f_flags;         /* The flags arg passed to open */
  295.         unsigned short f_count;         /* Number of opens on this file */
  296.         unsigned short f_reada;
  297.         struct inode * f_inode;         /* pointer to the inode struct */
  298.         struct file_operations * f_op;  /* pointer to the fops struct */
  299. };
  300.  
  301.  
  302. **************
  303. file_operations : Tells the kernel which function to call for
  304.                   which kernel function.
  305.  
  306. #include <linux/fs.h>
  307.  
  308. struct file_operations {
  309.         int (*lseek) (struct inode *, struct file *, off_t, int);
  310.         int (*read) (struct inode *, struct file *, char *, int);
  311.         int (*write) (struct inode *, struct file *, char *, int);
  312.         int (*readdir) (struct inode *, struct file *, struct dirent *, int);
  313.         int (*select) (struct inode *, struct file *, int, select_table *);
  314.         int (*ioctl) (struct inode *, struct file *, unsigned int, 
  315.                       unsigned int);
  316.         int (*mmap) (void);
  317.         int (*open) (struct inode *, struct file *);
  318.         void (*release) (struct inode *, struct file *);
  319.         int (*fsync) (struct inode *, struct file *);
  320. };
  321.  
  322.  
  323. **************
  324. inode : Information about the /dev/xxx file (or inode)
  325.  
  326. #include <linux/fs.h>
  327.  
  328. struct inode {
  329.         dev_t           i_dev;  
  330.         unsigned long   i_ino;  /* Inode number */
  331.         umode_t         i_mode; /* Mode of the file */
  332.         nlink_t         i_nlink;
  333.         uid_t           i_uid;
  334.         gid_t           i_gid;
  335.         dev_t           i_rdev;  /* Device major and minor numbers */
  336.         off_t           i_size;
  337.         time_t          i_atime;
  338.         time_t          i_mtime;
  339.         time_t          i_ctime;
  340.         unsigned long   i_blksize;
  341.         unsigned long   i_blocks;
  342.         struct inode_operations * i_op;
  343.         struct super_block * i_sb;
  344.         struct wait_queue * i_wait;
  345.         struct file_lock * i_flock;
  346.         struct vm_area_struct * i_mmap;
  347.         struct inode * i_next, * i_prev;
  348.         struct inode * i_hash_next, * i_hash_prev;
  349.         struct inode * i_bound_to, * i_bound_by;
  350.         unsigned short i_count;
  351.         unsigned short i_flags;  /* Mount flags (see fs.h) */
  352.         unsigned char i_lock;
  353.         unsigned char i_dirt;
  354.         unsigned char i_pipe;
  355.         unsigned char i_mount;
  356.         unsigned char i_seek;
  357.         unsigned char i_update;
  358.         union {
  359.                 struct pipe_inode_info pipe_i;
  360.                 struct minix_inode_info minix_i;
  361.                 struct ext_inode_info ext_i;
  362.                 struct msdos_inode_info msdos_i;
  363.                 struct iso_inode_info isofs_i;
  364.                 struct nfs_inode_info nfs_i;
  365.         } u;
  366. };
  367.  
  368. See Also: Driver Calls: MAJOR, MINOR, IS_RDONLY, IS_NOSUID, IS_NODEV,
  369.                         IS_NOEXEC, IS_SYNC
  370.  
  371. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  372.  
  373. Driver calls:
  374.  
  375.  
  376. **************
  377. add_timer : Cause a function to be executed when a given amount of time
  378.             has passed.
  379.  
  380. #include <linux/sched.h>
  381.  
  382. void add_timer(long jiffies, void (*fn)(void))
  383.  
  384. Arguments: jiffies -- The number of jiffies to time out after.
  385.            fn      -- The function in kernel space to run after timeout.
  386.  
  387. Note!  This is NOT process-specific!  If you are looking for a way
  388. to have a process go to sleep and timeout, look for ?
  389. Excessive use of this function will cause the kernel to panic if there are
  390. too many timeouts active at once.
  391.  
  392.  
  393. **************
  394. cli : Macro, Prevent interrupts from occuring
  395.  
  396. #include <asm/system.h>
  397.  
  398. #define cli() __asm__ __volatile__ ("cli"::)
  399.  
  400. See Also: sti
  401.  
  402.  
  403. **************
  404. free_irq : Free a registered interrupt
  405.  
  406. #include <linux/sched.h>
  407.  
  408. void free_irq(unsigned int irq)
  409.  
  410. Arguments: irq -- the interrupt level to free up
  411.  
  412. See Also: request_irq
  413.  
  414.  
  415. **************
  416. get_fs_byte, get_fs_word, get_fs_long : Get data from user space
  417.  
  418. Purpose: Allows a driver to access data in user space (which is in
  419.          a different segment than the kernel!)
  420.  
  421. #include <asm/segment.h>
  422.  
  423. inline unsigned char get_fs_byte(const char * addr)
  424. inline unsigned short get_fs_word(const unsigned short *addr)
  425. inline unsigned long get_fs_long(const unsigned long *addr)
  426.  
  427. Arguments: addr -- the address in user space to get data from
  428.  
  429. Returns: the value in user space.
  430.  
  431. See Also: memcpy_fromfs, memcpy_tofs, put_fs_byte, put_fs_word, put_fs_long
  432.  
  433.  
  434. **************
  435. inb, inb_p : Inputs a byte from a port
  436.  
  437. #include <asm/io.h>
  438.  
  439. inline unsigned int inb(unsigned short port)
  440. inline unsigned int inb_p(unsigned short port)
  441.  
  442. Arguments: port -- the port to input a byte from
  443.  
  444. Returns:  Byte received in the low byte.  High byte unused.
  445.  
  446. See Also: outb, outb_p
  447.  
  448.  
  449. **************
  450. IS_RDONLY, IS_NOSUID, IS_NODEV, IS_NOEXEC, IS_SYNC: Macros, check the status
  451.     of the device on the filesystem
  452.  
  453. #include <linux/fs.h>
  454.  
  455. #define IS_RDONLY(inode) (((inode)->i_sb) && ((inode)->i_sb->s_flags &
  456.                            MS_RDONLY))
  457. #define IS_NOSUID(inode) ((inode)->i_flags & MS_NOSUID)
  458. #define IS_NODEV(inode) ((inode)->i_flags & MS_NODEV)
  459. #define IS_NOEXEC(inode) ((inode)->i_flags & MS_NOEXEC)
  460. #define IS_SYNC(inode) ((inode)->i_flags & MS_SYNC)
  461.  
  462.  
  463. **************
  464. kfree, kfree_s : Free memory which has been kmalloced.
  465.  
  466. #include <linux/kernel.h>
  467.  
  468. #define kfree(x) kfree_s((x), 0)
  469. void kfree_s(void * obj, int size)
  470.  
  471. Arguments : obj  -- pointer to kernel memory you want to free
  472.             size -- size of block you want to free (0 if you don't know
  473.                     or are lazy -- slows things down)
  474.  
  475.  
  476. **************
  477. kmalloc : Allocate memory in kernel space
  478.  
  479. #include <linux/kernel.h>
  480.  
  481. void * kmalloc(unsigned int len, int priority)
  482.  
  483. Arguments: len      -- the length of the memory to allocate.  Must not be bigger
  484.                        than 4096.
  485.            priority -- GFP_KERNEL or GFP_ATOMIC.  GFP_ATOMIC causes kmalloc
  486.                        to return NULL if the memory could not be found
  487.                        immediately.  GFP_KERNEL is the usual priority.
  488.  
  489. Returns: NULL on failure, a pointer to kernel space on success.
  490.  
  491.  
  492. **************
  493. memcpy_fromfs, memcpy_tofs : Copies memory from user(fromfs)/kernel(tofs) 
  494.                              space to kernel/user space
  495.  
  496. #include <asm/segment.h>
  497.  
  498. inline void memcpy_fromfs(void * to, const void * from, unsigned long n)
  499. inline void memcpy_tofs(void * to, const void * from, unsigned long n)
  500.  
  501. Arguments: to   -- Address to copy data to
  502.            from -- Address to copy data from
  503.            n    -- number of bytes to copy
  504.  
  505. See Also: get_fs_byte, get_fs_word, get_fs_long,
  506.           put_fs_byte, put_fs_word, put_fs_long
  507.  
  508. Warning!  Get the order of arguments right!
  509.  
  510.  
  511. **************
  512. MAJOR, MINOR : Macros, get major/minor device number from inode i_dev entry.
  513.  
  514. #include <linux/fs.h>
  515.  
  516. #define MAJOR(a) (((unsigned)(a))>>8)
  517. #define MINOR(a) ((a)&0xff)
  518.  
  519.  
  520. **************
  521. outb, outb_p : Outputs a byte to a port
  522.  
  523. #include <asm/io.h>
  524.  
  525. inline void outb(char value, unsigned short port)
  526. inline void outb_p(char value, unsigned short port)
  527.  
  528. Arguments: value -- the byte to write out
  529.            port  -- the port to write it out on
  530.  
  531. See Also: inb, inb_p
  532.  
  533.  
  534. **************
  535. printk : Kernel printf
  536.  
  537. #include <linux/kernel.h>
  538.  
  539. int printk(const char *fmt, ...)
  540.  
  541. Arguments: fmt -- printf-style format
  542.            ... -- var-arguments, printf-style
  543.  
  544. Returns: Number of characters printed.
  545.  
  546.  
  547. **************
  548. put_fs_byte, put_fs_word, put_fs_long : Put data into user space
  549.  
  550. Purpose: Allows a driver to put a byte, word, or long into user space,
  551.          which is at a different segment than the kernel.
  552.  
  553. #include <asm/segment.h>
  554.  
  555. inline void put_fs_byte(char val,char *addr)
  556. inline void put_fs_word(short val,short * addr)
  557. inline void put_fs_long(unsigned long val,unsigned long * addr)
  558.  
  559. Arguments: addr -- the address in user space to get data from
  560.  
  561. Returns: the value in user space.
  562.  
  563. See Also: memcpy_fromfs, memcpy_tofs, get_fs_byte, get_fs_word, get_fs_long
  564.  
  565. Warning!  Get the order of arguments right!
  566.  
  567.  
  568. **************
  569. register_chrdev : Register a character device with the kernel
  570.  
  571. #include <linux/fs.h>
  572. #include <linux/errno.h>
  573.  
  574. int register_chrdev(unsigned int major, const char *name, 
  575.                            struct file_operations *fops)
  576.  
  577. Arguments: major -- the major device number to register as
  578.            name  -- the name of the device (currently unused)
  579.            fops  -- a file_operations structure for the device.
  580.  
  581. Returns: -EINVAL if major is >= MAX_CHRDEV (defined in fs.h as 32)
  582.          -EBUSY if major device has already been allocated
  583.          0 on success.
  584.  
  585.  
  586. **************
  587. request_irq : Request to perform a function on an interrupt
  588.  
  589. #include <linux/sched.h>
  590. #include <linux/errno.h>
  591.  
  592. int request_irq(unsigned int irq, void (*handler)(int))
  593.  
  594. Arguments: irq     -- the interrupt to request.
  595.            handler -- the function to handle the interrupt.  The interrupt
  596.                       handler should be of the form void handler(int).
  597.                       Unless you really know what you are doing, don't
  598.                       use the int argument.
  599.  
  600. Returns: -EINVAL if irq>15 or handler==NULL
  601.          -EBUSY if irq is already allocated.
  602.          0 on success.
  603.  
  604. See Also: free_irq
  605.  
  606.  
  607. **************
  608. select_wait : Add a process to the select-wait queue
  609.  
  610. #include <linux/sched.h>
  611.  
  612. inline void select_wait(struct wait_queue ** wait_address, select_table * p)
  613.  
  614. Arguments: wait_address -- Address of a wait_queue pointer
  615.            p            -- Address of a select_table
  616.  
  617. Devices which use select should define a struct wait_queue pointer and
  618. initialize it to NULL.  select_wait adds the current process to a circular
  619. list of waits.  The pointer to the circular list is wait_address.  If
  620. p is NULL, select_wait does nothing, otherwise the current process is
  621. put to sleep.
  622.  
  623. See Also: sleep_on, interruptible_sleep_on, wake_up, wake_up_interruptible
  624.  
  625.  
  626. **************
  627. sleep_on, interruptible_sleep_on : Put the current process to sleep.
  628.  
  629. #include <linux/sched.h>
  630.  
  631. void sleep_on(struct wait_queue ** p)
  632. void interruptible_sleep_on(struct wait_queue ** p)
  633.  
  634. Arguments: q -- Pointer to the driver's wait_queue (see select_wait)
  635.  
  636. sleep_on puts the current process to sleep in an uninterruptible state.
  637. That is, signals will not wake the process up.  The only thing which
  638. will wake a process up in this state is a hardware interrupt (which
  639. would call the interrupt handler of the driver) -- and even then the 
  640. interrupt routine needs to call wake_up to put the process in a running 
  641. state.
  642.  
  643. interruptible_sleep_on puts the current process to sleep in an interruptible
  644. state, which means that not only will hardware interrupts get through, but
  645. also signals and process timeouts ("alarms") will cause the process to
  646. wake up (and execute interrupt or signal handlers).  A call to 
  647. wake_up_interruptible is necessary to wake up the process and allow it
  648. to continue running where it left off.
  649.  
  650. See Also: select_wait, wake_up, wake_up_interruptible
  651.  
  652.  
  653. **************
  654. sti : Macro, Allow interrupts to occur
  655.  
  656. #include <asm/system.h>
  657.  
  658. #define sti() __asm__ __volatile__ ("sti"::)
  659.  
  660. See Also: cli
  661.  
  662.  
  663. **************
  664. sys_getegid, sys_getgid, sys_getpid, sys_getppid, sys_getuid, sys_geteuid :
  665.   Funky functions which get various information about the current process,
  666.  
  667. #include <linux/sys.h>
  668.  
  669. int sys_getegid(void)
  670. int sys_getgid(void)
  671. int sys_getpid(void)
  672. int sys_getppid(void)
  673. int sys_getuid(void)
  674. int sys_geteuid(void)
  675.  
  676. sys_getegid gets the effective gid of the process.
  677. sys_getgid gets the group ID of the process.
  678. sys_getpid gets the process ID of the process.
  679. sys_getppid gets the process ID of the process' parent.
  680. sys_geteuid gets the effective uid of the process.
  681. sys_getuid gets the user ID of the process.
  682.  
  683.  
  684. **************
  685. wake_up, wake_up_interruptible : Wake up _all_ processes waiting on
  686.                                  the wait queue.
  687.  
  688. #include <linux/sched.h>
  689.  
  690. void wake_up(struct wait_queue **q)
  691. void wake_up_interruptible(struct wait_queue **q)
  692.  
  693. Arguments: q -- Pointer to the driver's wait_queue (see select_wait)
  694.  
  695. See Also: select_wait, sleep_on, interruptible_sleep_on
  696.  
  697.  
  698. --------------------------------------------------------
  699.  
  700. ==========
  701. Some notes
  702. ==========
  703.  
  704. Interrupts, Drivers, and You!
  705. -----------------------------
  706.  
  707. First, a brief exposition on the Meaning of Interrupts.  There are three
  708. ways by which a program running in the CPU may be interrupted.  The first is
  709. the external interrupt.  This is caused by an external device (that is,
  710. external to the CPU) signalling for attention.  These are referred to as
  711. "interrupt requests" or "IRQs".
  712.  
  713. The second method is the exception, which is caused by something internal to
  714. the CPU, usually in response to a condition generated by execution of an
  715. instruction.
  716.  
  717. The third method is the software interrupt, which is a deliberately executed
  718. interrupt -- the INT instruction in assembly.  System calls are implemented
  719. using software interrupts; when a system call is desired, Linux places the
  720. system call number in EAX, and performs an INT 0x80 instruction.
  721.  
  722. Since drivers usually deal with hardware devices, it is logical that driver
  723. interrupts should refer to external interrupts.  There are 16 available IRQs
  724. -- IRQ0 through IRQ15.  The following table lists the official uses of the
  725. various IRQs:
  726.  
  727. IRQ0   -- timer 0
  728. IRQ1   -- keyboard
  729. IRQ2   -- AT slave 8259 ("cascade")
  730. IRQ3   -- COM2
  731. IRQ4   -- COM1
  732. IRQ5   -- LPT2
  733. IRQ6   -- floppy
  734. IRQ7   -- LPT1
  735. IRQ8-12   ??????
  736. IRQ13  -- coprocessor error
  737. IRQ14,15  ??????
  738.  
  739. Writing drivers which can be interrupted requires care.  Be aware that
  740. every line you write can be interrupted, and thus cause variable
  741. changes to occur.  If you really want to protect critical sections from
  742. being interrupted, use the cli() and sti() driver calls.
  743.  
  744. Suppose you wanted to test some kind of funky condition, where success of
  745. the condition leads to going to sleep, and being woken up by an interrupt.
  746. Consider this code:
  747.  
  748. void driver_interrupt(int unused)
  749. {
  750.   if (!driver_stuff.int_flag) return;  /* Spurious interrupts 
  751.                                           are not unheard of */
  752.   driver_stuff.int_flag=0;
  753.   weird_wacky(); /* Do some weird and wacky stuff 
  754.                     here to handle the interrupt */
  755.   disable_ints(); /* Disable the device from issuing interrupts */
  756.   wake_up(&driver_stuff.wait_queue); /* Sets process to TASK_RUNNING */
  757. }
  758.  
  759. if (conditions_are_ripe())
  760. {
  761.   driver_stuff.int_flag = 1;
  762.   enable_ints(); /* Enable device to interrupt us */
  763.   sleep_on(&driver_stuff.wait_queue); /* Sets process to TASK_UNINTERRUPTIBLE */
  764. }
  765.  
  766. Assume we just leave the conditions_are_ripe code, determining that the
  767. conditions are ripe!  We have just enabled the device to interrupt the
  768. machine.  So we are now about to enter the sleep_on code, and
  769. what should happen but the pesky device issues an interrupt.  Ka-chunk! and
  770. we enter the driver_interrupt routine, which does some weird and wacky
  771. stuff to handle the interrupt, and then we disable the device's interrupts.
  772. Ka-ching! we enter the wake_up function which sets the process up to run again.
  773. Boink! we exit the interrupt handler and commence where we left off 
  774. (just about to enter the sleep_on code). Vooosh! we're now sleeping the 
  775. process, awaiting an interrupt which will never occur, since the interrupt
  776. handler disabled the device from interrupts!  What to do?
  777.  
  778. Use cli() and sti() to protect the critical sections of code:
  779.  
  780. cli();
  781. if (conditions_are_ripe())
  782. {
  783.   driver_stuff.int_flag = 1;
  784.   enable_ints(); /* Enable device to interrupt us */
  785.   sleep_on(&driver_stuff.wait_queue); /* Sets process to TASK_UNINTERRUPTIBLE */
  786. }
  787. else sti();
  788.  
  789. First we clear interrupts.  This is not the same as disabling device
  790. interrupts!  This actually prevents a hardware interrupt from causing the
  791. CPU to execute interrupt code.  In effect, the interrupt is deferred.
  792.  
  793. Now we can do our check and perform sleep_on, secure in the knowledge that
  794. the interrupt handler cannot be called.  The sleep_on (and interruptible_
  795. sleep_on) call has a sti() in it in the right place, so you don't have to
  796. worry about calling sti() before sleep_on, and running into a race condition
  797. again.
  798.  
  799. Of course, with any interruptible device driver, you must be careful never
  800. to spend too much time in the interrupt routine if you are expecting more
  801. than one interrupt, because you may miss your second interrupt.
  802.  
  803. -=-=-=-=-=-=-
  804.  
  805. Drivers and signals:
  806. --------------------
  807.  
  808. When a process is sleeping in an interruptible state, any signal can wake it
  809. up.  This is the sequence of events which occurs when a sleeping process
  810. receives a signal:
  811.  
  812. (1) Set current->signal.
  813. (2) Set the process to a runnable state.
  814. (3) Execute the rest of the driver call.
  815. (4) Run the signal handler.
  816. (5) If the driver call in step 3 returned -ERESTARTNOHAND or -ERESTARTNOINTR,
  817.     then return from the driver call with EINTR.  If the driver call in step
  818.     3 returned -ERESTARTSYS, then restart the driver call.  Otherwise, just
  819.     return with whatever was returned from the driver call.
  820.  
  821. In the driver, you can tell if a sleep has been interrupted by a signal
  822. with the following code:
  823.  
  824.   if (current->signal & ~current->blocked)
  825.   {
  826.     /* Do things based on sleep interrupted by signal */
  827.   }
  828.  
  829. -=-=-=-=-=-=-
  830.  
  831. Drivers and timeouts:
  832. ---------------------
  833.  
  834. Suppose you wanted to sleep on an interrupt, but also time out after
  835. a period of time.  You could always use the add_timer, but that's 
  836. frowned upon because there are only a limited number of timers
  837. available -- currently there are 64.
  838.  
  839. The usual solution is to manually alter the current process's timeout:
  840.  
  841. current->timeout = jiffies + X;
  842. interruptible_sleep_on(&driver_stuff.wait_queue);
  843.  
  844. (Interruptible sleep_on must be used here to allow a timeout to interrupt
  845. the sleep).  This will cause the scheduler to set the task running again when 
  846. X jiffies has gone by.  Even if the timeout goes off and the process is
  847. allowed to continue running, it is probably a good idea to call
  848. wake_up_interruptible in case the process needs to be rescheduled.
  849.  
  850. To find out if it was a timeout which caused the process to wake up,
  851. check current->timeout.  If it is 0, a timeout occurred.  Otherwise it
  852. should remain what you set it at.  If a timeout did not occur, and something
  853. else woke the process up, you should set current->timeout to 0 to prevent
  854. the timeout from continuing.
  855.  
  856. The disadvantage of this method is that the process can only have one
  857. timeout at a time.  Over *all* drivers.
  858.  
  859.  
  860. -=-=-=-=-=-=-
  861.  
  862. The driver_select call:
  863. -----------------------
  864.  
  865. When a process issues a select call, it is checking to see if the given 
  866. devices are ready to perform the given operations.  For example, suppose
  867. you want a driver to have a command written to it, and to disallow further
  868. commands until the current command is complete.  Well, in the write call
  869. you would block commands if there is already a command operating (for example,
  870. waiting for a board to do something).  But that would require the process to
  871. write over and over again until it succeeds.  That just burns cycles.
  872.  
  873. The select call allows a process to determine the availability of read and
  874. write.  In the above example, one merely has to select for write on that
  875. device's file descriptor (as returned by open), and the process would be
  876. put to sleep until the device is ready to be written to.
  877.  
  878. The kernel will call the driver's driver_select call when the process issues a
  879. select call.  The arguments to the driver_select call are detailed above.
  880. If the wait argument is non-NULL, and there is no error condition caused
  881. by the select, driver_select should put the process to sleep, and arrange
  882. to be woken up when the device becomes ready (usually through an interrupt).
  883.  
  884. If, however, the wait argument is NULL, then the driver should quickly
  885. see if the device is ready, and return even if it is not.  The select_wait
  886. function does this already for you (see further).
  887.  
  888. Putting the process to sleep does not require calling a sleep_on function.
  889. It is the select_wait function which is called, with the p argument being
  890. equal to the wait argument passed to driver_select.
  891.  
  892. select_wait is pretty much equivalent to interruptible_sleep_on in that it
  893. adds the current process to the wait queue and sleeps the process in
  894. an interruptible state.  The internals of the differences between
  895. select_wait and interruptible_sleep_on are relatively irrelevant here.
  896. Suffice it to say that to wake the process up from the select, one needs
  897. to perform the wake_up_interruptible call.  When that happens, the
  898. process is free to run.  
  899.  
  900. However, in the case of interruptible_sleep_on, the process will continue
  901. running after the call to interruptible_sleep_on.  In the case of select_wait,
  902. the process does not.  driver_select is called as a "side effect" of the
  903. select call, and so completes even when it calls select_wait.  It is
  904. not select_wait which sleeps the process, but the select call.  Nevertheless,
  905. it is required to call select_wait to add the process to the wait-queue,
  906. since select will not do that.
  907.  
  908. All one needs to remember for driver_select is:
  909.  
  910. (1) Call select_wait if the device is not ready, and return 0.
  911. (2) Return 1 if the device is ready.
  912.  
  913.  
  914. Calling select with a timeout is really no different to the driver than
  915. calling it without select.  But there is one crucial difference.  Remember
  916. timing out on interrupts above?  Well, interrupt timeouts and select timeouts
  917. cannot co-exist.  They both use current->timeout to wake the process up
  918. after a period of time.  Remember that!
  919.  
  920.  
  921. -=-=-=-=-=-=-
  922.  
  923. Installation notes:
  924. -------------------
  925.  
  926. Before you sit down and write your first driver, first make sure you
  927. understand how to recompile the kernel.  Then go ahead and recompile it!
  928. Recompilation of the kernel is described in the FAQ.  If you can't
  929. recompile the kernel, you can't install your driver into the kernel.
  930. [Although I hear tell of a package on sunsite which can load and unload
  931. drivers while the kernel is running.  Until I test out this package,
  932. I won't include instructions for it here.]
  933.  
  934. For character devices, you need to go into the mem.c file in the
  935. (source)/linux/kernel/chr_dev directory, to the chr_dev_init function,
  936. and add your init function to it.  Recompile the kernel, and away you go!
  937.  
  938. (BTW, would you manually have to do a mknod to make the /dev/xxx entry
  939. for your driver?  Can you do it in the init function?)
  940.  
  941. In general, one installs a device special file in /dev manually, by using
  942. mknod:
  943.  
  944.   mknod /dev/xxx c major minor
  945.  
  946. If you registered your character driver as major device X, then all accesses
  947. to /dev/xxx where major==X will call your driver functions.
  948.